package com.zlm.common.util;

import com.zlm.common.base.PageEntity;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 分页工具类
 * @Author: duyufu
 * @Date: 2019/3/15 16:24
 */
public class PageUtils {
	/**
	 * 封装request参数 用于分页的实现方法
	 */
	public static PageEntity requestToPage(HttpServletRequest request) {
		PageEntity pageUtiles = new PageEntity();
		Map<String, Object> dtInfo = new HashMap<String, Object>();
		Enumeration<String> paramNames = request.getParameterNames();
		do {
			if (!paramNames.hasMoreElements()) {
				break;
			}
			String paramName = (String) paramNames.nextElement();
			String[] paramValue = request.getParameterValues(paramName);
			if (paramValue != null) {
				if (paramValue.length > 1) {
					dtInfo.put(paramName, paramValue);
				} else {
					if("pageSize".equals(paramName)) {
						dtInfo.put(paramName, Integer.parseInt(paramValue[0]));
						pageUtiles.setPageSize(Integer.parseInt(paramValue[0]));
					} else if ("pageNumber".equals(paramName)) {
						dtInfo.put(paramName, Integer.parseInt(paramValue[0]));
						pageUtiles.setPageNumber(Integer.parseInt(paramValue[0]));
					} else if(paramValue[0].length()>0){
						dtInfo.put(paramName, paramValue[0]);
					}else{
						dtInfo.put(paramName, null);
					}
				}
			}
		} while (true);
		if (dtInfo.get("pageNumber") != null && !"".equals(dtInfo.get("pageNumber")) && dtInfo.get("pageSize") != null && !"".equals(dtInfo.get("pageSize"))) {
			int pageNum = Integer.parseInt(String.valueOf(dtInfo.get("pageNumber")));
			int pageSize = Integer.parseInt(String.valueOf(dtInfo.get("pageSize")));
			dtInfo.put("pageNumber", (pageNum - 1) * pageSize);
		}
		return pageUtiles;
	}
}
